<template>
  <div>
    <a-card class="card-header">
      <div class="tool-bar">
        <a-button size="small" style="border: none;" @click="table.undo()" >
          <a-icon type="arrow-left" title="撤回" />
          撤回
        </a-button>
        <a-button size="small" style="border: none;" @click="table.redo()" >
          <a-icon type="arrow-right" title="恢复" />
          恢复
        </a-button>
        <a-button size="small" style="border: none;" @click="textLeft" >
          <a-icon type="pic-left" title="左对齐" />
          左对齐
        </a-button>
        <a-button size="small" style="border: none;" @click="textCenter" >
          <a-icon type="pic-center" title="居中对齐" />
          居中
        </a-button>
        <a-button size="small" style="border: none;" @click="textRight" >
          <a-icon type="pic-right" title="右对齐" />
          右对齐
        </a-button>
        <a-button size="small" style="border: none;" @click="topBorder" >
          <a-icon type="border-top" title="上边框" />
          上边框
        </a-button>
        <a-button size="small" style="border: none;" @click="bottomBorder" >
          <a-icon type="border-bottom" title="下边框" />
          下边框
        </a-button>
        <a-button size="small" style="border: none;" @click="leftBorder" >
          <a-icon type="border-left" title="左边框" />
          左边框
        </a-button>
        <a-button size="small" style="border: none;" @click="rightBorder" >
          <a-icon type="border-right" title="右边框" />
          右边框
        </a-button>
        <a-button size="small" style="border: none;" @click="boldFont" >
          <a-icon type="bold" title="字体加粗" />
          粗体
        </a-button>
        <!-- 字体大小 -->
        <a-button size="small" style="border: none;">
          <a-dropdown :trigger="['click']" title="字体大小" @click="e => e.preventDefault()">
            <a class="ant-dropdown-link" >
              <a-icon type="line-height" />
              字号
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-for="item in [10,15,20,25,30,35]" :key="item">
                <a @click="setFontSize(item)">{{ item }}px</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </a-button>
        <!-- 字体格式 -->
        <!-- <a-dropdown :trigger="['click']" title="字体样式">
          <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">
            <a-icon type="font-size" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item v-for="item in [10, 30]" :key="item">
              <a>{{ item }} px</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown> -->
        <a-button size="small" style="border: none;" >
          <div ref="color">
            <a-icon type="font-colors" title="更改字体颜色" />
            颜色
          </div>
        </a-button>
        <a-button size="small" style="border: none;" >
          <div ref="bgColor">
            <a-icon type="bg-colors" title="更改背景颜色" />
            背景色
          </div>
        </a-button>
        <!-- <a-icon type="check-square" title="多选框" @click="setCheckBox" /> -->
        <a-button size="small" style="border: none;" @click="setDate" >
          <a-icon type="calendar" title="插入日期" />
          日期
        </a-button>
        <a-button size="small" style="border: none;" @click="setDropDown" >
          <a-icon type="bars" title="插入下拉框" />
          下拉框
        </a-button>
        <a-button size="small" style="border: none;" @click="inputExecl" >
          <a-icon type="folder-add" title="导入execl" />
          导入
        </a-button>
        <a-button size="small" style="border: none;" @click="saveToServe" >
          <a-icon type="cloud-upload" title="保存" />
          保存
        </a-button>
        <a-button size="small" style="border: none;" @click="doPrint" >
          <a-icon type="printer" title="打印选中" />
          打印
        </a-button>
      </div>
      <DropDownModel ref="DropDown" @ok="DropDwonInputOk"></DropDownModel>
      <UploadImageModal
        ref="UploadImage"
        @ok="UploadImageOK"
      ></UploadImageModal>
      <div id="Excel" ref="spreadsheet"></div>
      <!-- 打印模板区 -->
      <div ref="tableRef" v-show="false">
        <PrintTemp :print-data="prints"></PrintTemp>
      </div>
    </a-card>
  </div>
</template>

<script>
import XLSX from "xlsx";
import jexcel from "jspreadsheet-ce";
import "jspreadsheet-ce/dist/jspreadsheet.css";
import "jsuites/dist/jsuites.css";
import DropDownModel from "./components/DropDownModal.vue";
import PrintTemp from "./components/printTemp";
import UploadImageModal from "./components/UploadImageModal.vue";
import { tableOption, content } from "./components/optionsConfig";
import api from "@/api/apiServer";
import { apiUrl } from "@/api/URLConfig";
import axois from "axios";
import moment from "moment";
import jSuites from "jsuites";

export default {
  components: {
    PrintTemp,
    DropDownModel,
    UploadImageModal,
  },
  data() {
    return {
      id: "",
      productPlan: "",
      headName: {},
      prints: {
        "工艺-1": "",
        "工艺-2": "",
        "工艺-3": "",
        "工艺-4": "",
        "工艺-5": "",
        "工艺-6": "",
        "工艺-7": "",
        "工艺-8": "",
        "工艺-9": "",
        "工艺-10": "",
      },
      setWidthCol: [
        "图纸接收日期",
        "开始加工日期",
        "交货日",
        "交期",
        "入库时间",
        "协调交期",
        "工件图片",
      ],
      excelData: [],
    };
  },
  mounted() {
    let that = this;
    this.id = Number(this.$route.query.id);
    this.getExeclData({ id: this.id });
    content.scoop = this;
    window.table = jexcel(this.$refs.spreadsheet, tableOption);
    Object.assign(this, { table });
    jSuites.color(this.$refs.color, {
      resetLabel: "重置",
      doneLabel: "完成",
      onchange: function(e, color) {
        that.setCellStyle("color", color);
      },
    });
    jSuites.color(this.$refs.bgColor, {
      resetLabel: "重置",
      doneLabel: "完成",
      onchange: function(e, color) {
        that.setCellStyle("background-color", color);
      },
    });
    window.table.refresh();
  },
  methods: {
    //表格渲染函数
    renderData(headData, tableDate) {
      //渲染表头
      // headData.forEach((item, index) => {
      //   window.table.setHeader(index, item);
      // });
      //渲染表体
      tableDate.unshift(headData);
      window.table.setData(tableDate);
      window.table.options.data[0].forEach((element, index) => {
        this.setWidthCol.includes(element) &&
          window.table.setWidth(index, "165");
      });
      window.table.refresh();
    },
    //保存到服务器
    async saveToServe() {
      // 获取并上传表头
      // let headData = {};
      // window.table
      //   .getHeaders()
      //   .split(",")
      //   .forEach((item, index) => {
      //     headData[index] = item;
      //   });
      // let titleRes = await api.AddOrUpdataTableHead(headData);

      //获取并上传表格数据
      let tableData = [];
      //筛出空数据并保存到数组
      window.table.getJson().forEach((element) => {
        let str = element[6] + "";
        if (str.trim()) {
          tableData.push(element);
        }
      });
      tableData.shift()
      let execlData = JSON.stringify(tableData);
      // let execlData = tableData;
      let params = {
        id: content.scoop.id,
        productPlan: content.scoop.productPlan,
        excelData: execlData,
      };
      let res = await api.ProductPlanV2Update(params);
      content.scoop.$message.success(res.message);
      console.log(res);
    },
    //获取execl数据
    async getExeclData(params) {
      //获取表头数据
      let headRes = await api.FindTableHead();
      let _head = JSON.parse(headRes.data.data);
      this.headName = _head;
      let headData = [];
      for (let item in _head) {
        headData[~~item] = _head[item];
      }
      //获取表格数据
      let res = await api.ProductPlanV2GetDetail(params);
      this.productPlan = res.data.productPlan;
      this.excelData = JSON.parse(res.data.excelData);
      this.renderData(headData, this.excelData);
    },
    // 获取打印数据
    doPrint() {
      //提取表格中要打印的数据
      let printData = [];
      let start = window.table.selectedContainer[1];
      let end = window.table.selectedContainer[3];
      for (let i = start; i <= end; i++) {
        console.log(window.table.options.data[i][0]);
        if(!window.table.options.data[i][0]=="序号"||window.table.options.data[i][0]){
          printData.push(window.table.options.data[i]);
        }
      }
      if(printData.length < 1){
        this.$message.error("暂无可打印的数据")
        return false;
      }
      this.printSelectData(printData);
    },
    //打印选中数据
    printSelectData(printArr) {
      let that = this;
      window.onafterprint = function() {
        if (printArr.length > 1) {
          that.printSelectData(printArr.slice(1));
        } else {
          window.location.reload();
        }
      };

      let _printobj = {};
      console.log(printArr[0]);
      for (let item in printArr[0]) {
        _printobj[this.headName[item]]=printArr[0][item]
      }
      _printobj.id = this.id;

      this.prints = _printobj;
      setTimeout(() => {
        let newstr = this.$refs.tableRef.innerHTML; // 获取需要打印的内容
        document.body.innerHTML = newstr;
        window.print();
      }, 200);
    },
    //导入Execl
    inputExecl() {
      let that = this;
      let execlInput = document.createElement("input");
      execlInput.type = "file";
      execlInput.click();
      execlInput.addEventListener("change", function(e) {
        that.load(execlInput);
      });
    },
    //读取本地execl函数
    load(inputEl) {
      let wb;
      let that = this;
      let tableData = [[]];
      let obj = inputEl;
      if (!obj.files) {
        return;
      }
      let f = obj.files[0];
      let reader = new FileReader();
      reader.onload = function(e) {
        let data = e.target.result;
        wb = XLSX.read(data, {
          type: "binary", //以二进制的方式读取
          cellStyles: true,
        });
        console.log("wb: ", wb);
        //读取并设置表头
        let headReg = /^__EMPTY/;
        let headData = [];
        for (const key in XLSX.utils.sheet_to_json(
          wb.Sheets[wb.SheetNames[0]],
          {
            head: 0,
            defval: " ",
          }
        )[0]) {
          if (!headReg.test(key)) {
            headData.push(key.trim());
          }
        }
        headData.splice(3, 0, "工件图片");

        XLSX.utils
          .sheet_to_json(wb.Sheets[wb.SheetNames[0]], { head: 0, defval: " " })
          .forEach((item) => {
            let itemArr = [];
            for (const key in item) {
              if (!headReg.test(key)) {
                itemArr.push(item[key]);
              }
            }
            itemArr.splice(3, 0, "");
            tableData.push(itemArr);
          });
        tableData.shift();
        that.renderData(headData, tableData);
      };
      reader.readAsBinaryString(f);
    },
    //上传图片完成
    UploadImageOK(imgData) {
      let td = this.table.tbody.children[this.table.selectedContainer[1]]
        .children[this.table.selectedContainer[0] + 1];

      let cellName = jexcel.getColumnNameFromId([
        this.table.selectedContainer[0],
        parseInt(this.table.selectedContainer[1]),
      ]);
      window.table.setValue(cellName, apiUrl + imgData, false);
      //将单元格的值设置为图片
      let img = document.createElement("img");
      img.src = apiUrl + imgData;
      img.title = imgData;
      td.innerHTML = "";
      td.appendChild(img);
    },
    //上传图片
    uploadImage() {
      let that = this;
      let imgInput = document.createElement("input");
      imgInput.type = "file";
      imgInput.click();
      imgInput.onchange = async function() {
        let file = imgInput.files[0];
        const isJpgOrPng =
          file.type === "image/jpeg" || file.type === "image/png";
        if (!isJpgOrPng) {
          that.$message.error("只能上传jpg,png!");
          return false;
        }
        const isLt2M = file.size / 1024 / 1024 < 20;
        if (!isLt2M) {
          that.$message.error("文件最大20MB!");
          return false;
        }
        let formData = new FormData();
        formData.append("file", imgInput.files[0]);
        let res = await axois.post(apiUrl + "/fileLocal/uploads", formData);
        if (res.data.code == 200) {
          that.$message.success(res.data.message);
          that.UploadImageOK(res.data.data);
        } else {
          that.$message.error(res.data.message);
        }
      };
    },
    //设置单元格样式
    setCellStyle(attr, value) {
      let userSelectArea = window.table.selectedContainer;
      
      for (let i = userSelectArea[0]; i <= userSelectArea[2]; i++) {
        for (let j = userSelectArea[1]; j <= userSelectArea[3]; j++) {
          let cellName = jexcel.getColumnNameFromId([i, parseInt(j)]);
          window.table.setStyle(cellName, attr, value);
        }
      }
    },
    textLeft() {
      this.setCellStyle("text-align", "left");
    },
    textRight() {
      this.setCellStyle("text-align", "right");
    },
    textCenter() {
      this.setCellStyle("text-align", "center");
    },
    topBorder() {
      this.setCellStyle("border-top", "1px solid black");
    },
    bottomBorder() {
      this.setCellStyle("border-bottom", "1px solid black");
    },
    leftBorder() {
      this.setCellStyle("border-left", "1px solid black");
    },
    rightBorder() {
      this.setCellStyle("border-right", "1px solid black");
    },
    boldFont() {
      this.setCellStyle("font-weight", "bold");
    },
    setFontSize(size) {
      this.setCellStyle("font-size", size + "px");
    },
    setDate() {
      let td =
        window.table.tbody.children[~~window.table.selectedContainer[1]]
          .children[~~window.table.selectedContainer[0] + 1];
      var info = td.getBoundingClientRect();
      var editor = document.createElement("div");
      editor.style.width = info.width + "px";
      editor.style.height = info.height - 2 + "px";
      editor.style.minHeight = info.height - 2 + "px";
      td.classList.add("editor");
      td.innerHTML = "";
      td.appendChild(editor);

      let input = document.createElement("input");
      td.innerHTML = "";
      td.append(input);

      // 初始化时间
      window.table.options.data[~~window.table.selectedContainer[1]][
        ~~window.table.selectedContainer[0]
      ] = moment().format("YYYY-MM-DD HH:mm:ss");

      jSuites.calendar(td.children[0], {
        format: "YYYY/MM/DD HH:MM:SS",
        time: true,
        today: true,
        months: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        monthsFull: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        weekdays: ["日", "一", "二", "三", "四", "五", "六"],
        textReset: "重置",
        textDone: "完成",
        textUpdate: "更新",
        onchange: function(e, afterTime) {
          window.table.options.data[~~window.table.selectedContainer[1]][
            ~~window.table.selectedContainer[0]
          ] = afterTime;
        },
      });
      window.table.setWidth(window.table.selectedContainer[0], "165");
    },
    setDropDown() {
      this.$refs.DropDown.modalShow();
    },
    DropDwonInputOk(str) {
      let data = [];
      str.split(";").forEach((item, index) => {
        let obj = {};
        obj.value = item + "";
        obj.text = item + "";
        data.push(obj);
      });
      let td = this.table.tbody.children[this.table.selectedContainer[1]]
        .children[this.table.selectedContainer[0] + 1];

      var info = td.getBoundingClientRect();
      var editor = document.createElement("div");
      editor.style.width = info.width + "px";
      editor.style.height = info.height - 2 + "px";
      editor.style.minHeight = info.height - 2 + "px";
      td.classList.add("editor");
      td.innerHTML = "";
      td.appendChild(editor);

      let div = document.createElement("div");
      td.innerHTML = "";
      td.append(div);

      jSuites.dropdown(td.children[0], {
        data: data,
      });
    },
  },
};
</script>
<style lang="less" scoped>
.color-box {
  position: relative;
}
.color-select {
  position: absolute;
  bottom: 0;
}
::v-deep .jexcel_toolbar {
  & > i {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 3px;
  }
}
#app {
  width: 100%;
}
.tool-bar {
  height: 32px;
  display: flex;
  align-items: center;
  // border: 1px solid #ccc;
  padding: 4px;
  margin: 0px 2px 4px 1px;
  top: 0px;
  i:hover {
    background-color: #f3f3f3;
  }
  // i {
  //   display: flex;
  //   justify-content: center;
  //   align-items: center;
  //   height: 26px;
  //   width: 26px;
  //   margin-left: 5px;
  // }
  // a {
  //   display: flex;
  //   width: 32px;
  //   color: #595959;
  // }
}

.card-header {
  margin: 20px 0;
}

::v-deep .jexcel_toolbar {
  & > i {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 3px;
  }
}
::v-deep .jexcel_search {
  box-sizing: border-box;
  border: 1px solid lightgray;
  border-radius: 15px;
  padding: 2px 10px;
}
</style>
